import { useState, useEffect } from 'react';
import { fileToBase64, BackgroundStorage } from '@/lib/utils';
import { cn } from '@/lib/utils';

interface BackgroundSettingsProps {
  isOpen: boolean;
  onClose: () => void;
  onBackgroundChange: (imageData: string | null) => void;
}



export default function BackgroundSettings({ isOpen, onClose, onBackgroundChange }: BackgroundSettingsProps) {
  const [selectedBackground, setSelectedBackground] = useState<string | null>(null);
  const [uploadProgress, setUploadProgress] = useState<number | null>(null);
  const [activeTab, setActiveTab] = useState<'upload' | 'preset'>('preset');
  
  // 从本地存储加载当前背景
  useEffect(() => {
    if (isOpen) {
      const currentBg = BackgroundStorage.get();
      setSelectedBackground(currentBg);
    }
  }, [isOpen]);
  
  // 处理图片上传
  const handleImageUpload = async (e: React.ChangeEvent<HTMLInputElement>) => {
    const file = e.target.files?.[0];
    if (!file) return;
    
    // 检查文件类型
    if (!file.type.startsWith('image/')) {
      alert('请上传图片文件');
      return;
    }
    
    try {
      setUploadProgress(0);
      // 模拟上传进度
      const progressInterval = setInterval(() => {
        setUploadProgress(prev => {
          if (prev === null) return null;
          const newProgress = prev + 10;
          if (newProgress >= 100) {
            clearInterval(progressInterval);
            return 100;
          }
          return newProgress;
        });
      }, 100);
      
      const base64Data = await fileToBase64(file);
      BackgroundStorage.set(base64Data);
      setSelectedBackground(base64Data);
      onBackgroundChange(base64Data);
      
      // 重置上传进度和input值
      setTimeout(() => {
        setUploadProgress(null);
        if (e.target) e.target.value = '';
      }, 1000);
    } catch (error) {
      console.error('图片上传失败:', error);
      alert('图片上传失败，请重试');
      setUploadProgress(null);
    }
  };
  
  // 选择预设背景
  const handlePresetSelect = (url: string) => {
    BackgroundStorage.set(url);
    setSelectedBackground(url);
    onBackgroundChange(url);
  };
  
  // 移除自定义背景
  const handleRemoveBackground = () => {
    BackgroundStorage.remove();
    setSelectedBackground(null);
    onBackgroundChange(null);
  };
  
  if (!isOpen) return null;
  
  return (
    <div className="fixed inset-0 bg-black/50 z-50 flex items-center justify-center p-4" onClick={onClose}>
      <div 
        className="bg-white dark:bg-gray-800 rounded-2xl shadow-2xl w-full max-w-md max-h-[80vh] overflow-y-auto"
        onClick={(e) => e.stopPropagation()}
      >
        {/* 头部 */}
        <div className="p-5 border-b border-gray-200 dark:border-gray-700 flex justify-between items-center">
          <h3 className="text-xl font-semibold text-gray-900 dark:text-white">背景设置</h3>
          <button 
            onClick={onClose}
            className="text-gray-500 hover:text-gray-700 dark:text-gray-400 dark:hover:text-gray-200"
          >
            <i className="fa-solid fa-times"></i>
          </button>
        </div>
        
        {/* 内容区 */}
        <div className="p-5">
          {/* 选项卡 */}
          <div className="flex border-b border-gray-200 dark:border-gray-700 mb-5">
            <button
              className={cn(
                "py-2 px-4 text-sm font-medium",
                activeTab === 'preset' 
                  ? "text-blue-600 dark:text-blue-400 border-b-2 border-blue-600 dark:border-blue-400" 
                  : "text-gray-500 dark:text-gray-400 hover:text-gray-700 dark:hover:text-gray-300"
              )}
              onClick={() => setActiveTab('preset')}
            >
              预设背景
            </button>
            <button
              className={cn(
                "py-2 px-4 text-sm font-medium",
                activeTab === 'upload' 
                  ? "text-blue-600 dark:text-blue-400 border-b-2 border-blue-600 dark:border-blue-400" 
                  : "text-gray-500 dark:text-gray-400 hover:text-gray-700 dark:hover:text-gray-300"
              )}
              onClick={() => setActiveTab('upload')}
            >
              上传图片
            </button>
          </div>
          
          {/* 预设背景 */}
          {activeTab === 'preset' && (
            <div className="grid grid-cols-2 gap-4">
              {presetBackgrounds.map(background => (
                <div key={background.id} className="group relative">
                  <div className="aspect-video rounded-lg overflow-hidden border-2 border-transparent group-hover:border-blue-500 transition-all cursor-pointer">
                    <img 
                      src={background.url} 
                      alt={background.name}
                      className="w-full h-full object-cover"
                    />
                    {selectedBackground === background.url && (
                      <div className="absolute inset-0 bg-black/30 flex items-center justify-center">
                        <i className="fa-solid fa-check text-white text-xl"></i>
                      </div>
                    )}
                  </div>
                  <p className="text-xs text-center mt-1 text-gray-700 dark:text-gray-300">{background.name}</p>
                  <button 
                    className="absolute inset-0 w-full h-full"
                    onClick={() => handlePresetSelect(background.url)}
                  />
                </div>
              ))}
            </div>
          )}
          
          {/* 上传图片 */}
          {activeTab === 'upload' && (
            <div className="space-y-4">
              <label className="flex flex-col items-center justify-center w-full h-48 border-2 border-dashed border-gray-300 dark:border-gray-600 rounded-lg cursor-pointer bg-gray-50 dark:bg-gray-700/50 hover:bg-gray-100 dark:hover:bg-gray-700 transition-colors">
                <div className="flex flex-col items-center justify-center pt-5 pb-6 w-full text-center">
                  <i className="fa-solid fa-cloud-upload text-3xl text-gray-400 mb-2"></i>
                  <p className="mb-1 text-sm text-gray-600 dark:text-gray-300">点击上传或拖放图片</p>
                  <p className="text-xs text-gray-500 dark:text-gray-400">支持 JPG, PNG, WEBP (最大 5MB)</p>
                </div>
                <input type="file" accept="image/*" className="hidden" onChange={handleImageUpload} />
                
                {/* 上传进度条 */}
                {uploadProgress !== null && (
                  <div className="absolute bottom-0 left-0 right-0 h-1 bg-gray-200 dark:bg-gray-600">
                    <div 
                      className="h-full bg-blue-500" 
                      style={{ width: `${uploadProgress}%` }}
                    ></div>
                  </div>
                )}
              </label>
              
              {uploadProgress === 100 && (
                <div className="text-center py-2 text-green-500 text-sm">
                  <i className="fa-solid fa-check-circle mr-1"></i> 图片上传成功！
                </div>
              )}
            </div>
          )}
          
          {/* 当前背景预览 */}
          {selectedBackground && (
            <div className="mt-6 pt-6 border-t border-gray-200 dark:border-gray-700">
              <h4 className="text-sm font-medium text-gray-700 dark:text-gray-300 mb-2">当前背景预览</h4>
              <div className="aspect-video rounded-lg overflow-hidden relative">
                <img 
                  src={selectedBackground} 
                  alt="当前背景"
                  className="w-full h-full object-cover"
                />
                <button 
                  onClick={handleRemoveBackground}
                  className="absolute top-2 right-2 bg-black/50 hover:bg-black/70 text-white p-1 rounded-full transition-colors"
                  title="移除背景"
                >
                  <i className="fa-solid fa-trash"></i>
                </button>
              </div>
            </div>
          )}
        </div>
      </div>
    </div>
  );
}
interface PresetBackground {
  id: string;
  name: string;
  url: string;
}

// 预设背景图片数据
const presetBackgrounds: PresetBackground[] = [
  {
    id: 'bg1',
    name: '山脉风景',
    url: 'https://space.coze.cn/api/coze_space/gen_image?image_size=landscape_16_9&prompt=beautiful%20mountain%20landscape%2C%20sunset%2C%20nature%2C%204k%20photography&sign=6ececa3f1aecfd0f6807164de1cfaf7a'
  },
  {
    id: 'bg2',
    name: '海洋日落',
    url: 'https://space.coze.cn/api/coze_space/gen_image?image_size=landscape_16_9&prompt=ocean%20sunset%2C%20seaside%2C%20calm%2C%204k%20photography&sign=a2870b587ae0cc88fb4a59dad2bc593e'
  },
  {
    id: 'bg3',
    name: '森林小径',
    url: 'https://space.coze.cn/api/coze_space/gen_image?image_size=landscape_16_9&prompt=forest%20path%2C%20morning%20mist%2C%20green%20trees%2C%204k%20photography&sign=a021b60cf58ab396aeef8ae75d04c527'
  },
  {
    id: 'bg4',
    name: '星空夜景',
    url: 'https://space.coze.cn/api/coze_space/gen_image?image_size=landscape_16_9&prompt=starry%20night%2C%20milky%20way%2C%20mountains%2C%204k%20photography&sign=bd50c7e681cb2ca0e4e95551717ed8b1'
  },
  {
    id: 'bg5',
    name: '城市天际线',
    url: 'https://space.coze.cn/api/coze_space/gen_image?image_size=landscape_16_9&prompt=modern%20city%20skyline%2C%20night%20view%2C%20illuminated%2C%204k%20photography&sign=ef7e695886777c745bbb53d071ed1f3f'
  },
  {
    id: 'bg6',
    name: '沙漠风光',
    url: 'https://space.coze.cn/api/coze_space/gen_image?image_size=landscape_16_9&prompt=desert%20landscape%2C%20sand%20dunes%2C%20sunrise%2C%204k%20photography&sign=cf5f945f08717fd18778e30bb3708365'
  }
];
